package com.gcloud.mesh.dcs.chain.huawei;

import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import com.gcloud.mesh.dcs.dao.SchedulerStepDao;
import com.gcloud.mesh.dcs.entity.SchedulerStepEntity;
import com.gcloud.mesh.dcs.strategy.huawei.ShowTaskSolution;
import com.gcloud.mesh.header.param.HuaweiMigrationParam;
import com.huaweicloud.sdk.core.auth.GlobalCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.sms.v3.SmsClient;
import com.huaweicloud.sdk.sms.v3.model.*;
import com.huaweicloud.sdk.sms.v3.region.SmsRegion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.MyBusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

//@Component
@Slf4j
public class StartTask_4 extends AbstractHuaweiMigrationStep{

    @Autowired
    private ShowTaskSolution showTaskSolution;

    @Autowired
    private SchedulerStepDao schedulerStepDao;

    @Override
    public boolean checkStatus(String stepId) {
        SchedulerStepEntity stepEntity = schedulerStepDao.getById(stepId);
        JSONObject json = JSONObject.parseObject(stepEntity.getAttach());
        String accessKeyId = json.getString("accessKeyId");
        String accessSecret = json.getString("accessSecret");
        String taskId = json.getString("taskId");
        ShowTaskResponse res = showTaskSolution.showTask(accessKeyId, accessSecret, taskId);
        PostSourceServerBody sourceServer = res.getSourceServer();
        //获取所有迁移进程,当最后一个进程结束调用启动目标端
        if("syncing".equals(sourceServer.getState())) {
            updateTask(accessKeyId, accessSecret, taskId, "test");
        }
        if("error".equals(sourceServer.getState())) {
        	throw new MyBusinessException("华为云迁移任务状态错误");
        }
        return res.getFinishDate()!=null;
    }

    @Override
    public boolean isSyncChain() {
        return false;
    }

    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        HuaweiMigrationParam huaweiMigrationParam = JSONObject.toJavaObject(jsonObject,HuaweiMigrationParam.class);
        String taskId = jsonObject.getString("taskId");
        updateTask(huaweiMigrationParam.getAccessKey(), huaweiMigrationParam.getSecretKey(), taskId, "start");
        filterChain.doExec(schedulerJobId,jsonObject.toString(),filterChain,stepChain);
    }

    @Override
    public String chainName(String attach) {
        return "启动迁移任务";
    }

    @Override
    public int getOrder() {
        return 4;
    }


    private UpdateTaskStatusResponse updateTask(String ak, String sk, String taskId, String action) {
        if(StringUtils.isBlank(ak)) {
            ak = "8QVISVT4XJHUNMIEPZBQ";
        }
        if(StringUtils.isBlank(sk)) {
            sk = "GingsSlHInSkQ3x47jMSEjFT0uumSJgplZs926Cw";
        }
        if(StringUtils.isBlank(taskId)) {
            taskId = "ff3b0bd1-c37d-40d0-8bae-b4302f398222";
        }
        UpdateTaskStatusResponse response = null;
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        config.withIgnoreSSLVerification(true);
        ICredential auth = new GlobalCredentials()
                .withAk(ak)
                .withSk(sk);

        SmsClient client = SmsClient.newBuilder()
                .withCredential(auth)
                .withHttpConfig(config)
                .withRegion(SmsRegion.valueOf("ap-southeast-1"))
                .build();
        UpdateTaskStatusRequest request = new UpdateTaskStatusRequest();
        request.withTaskId(taskId);
        UpdateTaskStatusReq body = new UpdateTaskStatusReq();
        body.withOperation(UpdateTaskStatusReq.OperationEnum.fromValue(action));
        request.withBody(body);
        try {
            response = client.updateTaskStatus(request);
//           System.out.println(response.toString());
        } catch (ConnectionException e) {
            log.error("迁移开始任务连接失败："+ e);
//           e.printStackTrace();
        } catch (RequestTimeoutException e) {
            log.error("迁移开始任务超时失败："+ e);
//           e.printStackTrace();
        } catch (ServiceResponseException e) {
            log.error("迁移开始任务失败："+ e);
//           e.printStackTrace();
//           System.out.println(e.getHttpStatusCode());
//           System.out.println(e.getErrorCode());
//           System.out.println(e.getErrorMsg());
        }
        return response;
    }
}
